/*
 蓝牙遥控Arduino小车程序
 功能：小车接收到蓝牙模块发送过来的字符“G”前进，字符“B”后退，字符“L”左转，字符“R”右转，字符“S”停止。
 */

#define PWA 3
#define PWB 11
#define DIRA 12
#define DIRB 13
#define BRAKEA 9
#define BRAKEB 8 

char FORWARD = 'G';
char BACK = 'B';
char RIGHT = 'R';
char LEFT = 'L';
char STOP = 'S';
char CIRCLE = 'C';
char SQUARE = 'Q';
char LINE = 'F';

void setup()
{
  pinMode(PWA,OUTPUT);
  pinMode(PWB,OUTPUT);
  pinMode(DIRA,OUTPUT);
  pinMode(DIRB,OUTPUT);
  pinMode(BRAKEA,OUTPUT);
  pinMode(BRAKEB,OUTPUT);
  
  Serial.begin(9600);
}

char readSignal() {
  char comdata = 0;
  while (Serial.available())
  {
    comdata = Serial.read();
    delay(2);
  }
  return comdata;
}

void goCircle(){
  Serial.println("CIRCLE");
  analogWrite(PWA,180);
  analogWrite(PWB,100);
  digitalWrite(DIRA,HIGH);
  digitalWrite(BRAKEA,LOW);
  digitalWrite(DIRB,HIGH);
  digitalWrite(BRAKEB,LOW);
}

void goForward(){
  Serial.println("GO");
  analogWrite(PWA,180);
  analogWrite(PWB,180);
  digitalWrite(DIRA,HIGH);
  digitalWrite(BRAKEA,LOW);
  digitalWrite(DIRB,HIGH);
  digitalWrite(BRAKEB,LOW);
}

void goBack(){
  Serial.println("BACK");
  analogWrite(PWA,180);
  analogWrite(PWB,180);
  digitalWrite(DIRA,LOW);
  digitalWrite(BRAKEA,LOW);
  digitalWrite(DIRB,LOW);
  digitalWrite(BRAKEB,LOW);
}

void turnLeft(){
  Serial.println("LEFT");
  analogWrite(PWA,120);
  analogWrite(PWB,120);
  digitalWrite(DIRA,LOW);
  digitalWrite(BRAKEA,LOW);
  digitalWrite(DIRB,HIGH);
  digitalWrite(BRAKEB,LOW);
}

void turnRight(){
  Serial.println("RIGHT");
  analogWrite(PWA,120);
  analogWrite(PWB,120);
  digitalWrite(DIRA,HIGH);
  digitalWrite(BRAKEA,LOW);
  digitalWrite(DIRB,LOW);
  digitalWrite(BRAKEB,LOW);
}

void goStop(){
  Serial.println("STOP");
  analogWrite(PWA,0);
  analogWrite(PWB,0);
  digitalWrite(DIRA,LOW);
  digitalWrite(BRAKEA,HIGH);
  digitalWrite(DIRB,LOW);
  digitalWrite(BRAKEB,HIGH);
}

void goLine(){
  goForward();
  delay(3000);
  goBack();
  delay(3000);
}

void goSquare(){
  turnLeft();
  delay(500);
  goForward();
  delay(2000);
}


void loop()//主循环函数
{
  
  static char s;
  char flag = readSignal();
  if(flag != 0)s = flag;
  
  if (s == FORWARD ) {
      goForward();
  }

  if (s == LEFT ) {
    turnLeft();
  }
  
  if (s == STOP ) {
    goStop();
  }
  
  if (s == RIGHT ) {
    turnRight();
  }
  
  if (s == BACK ) {
    goBack();
  }
  
  if (s == CIRCLE ) {
    goCircle();
  }
  
  if (s == SQUARE ) {
    goSquare();
  }
  
  if (s == LINE ) {
    goLine();
  }
}

